package a.student.dao;

import java.util.ArrayList;
import a.student.dto.Student;
import a.student.helper.DatabaseHelper;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class StudentDao extends BaseDao<Student>{

	public StudentDao(Context context, String databaseName) {
		super(context, databaseName);
	}
	
	public StudentDao(SQLiteDatabase db) {
		super(db);
	}
	
	public StudentDao(DatabaseHelper helper) {
		super(helper);
	}
	
	public long insert(Student student) {
        ContentValues values = new ContentValues();
        values.put(Student.STUDENT_ID, student.getStudentId());
        values.put(Student.STUDENT_NAME, student.getStudentName());
        values.put(Student.ADDRESS, student.getAddress());
        long result = super.insert(Student.TABLE_NAME, values);
        if(result>0)
        	student.setStudentId((int)result);
        return result;
    }


    public long delete(Student student) {
    	ContentValues contentValues = new ContentValues();
    	contentValues.put(Student.STUDENT_ID, student.getStudentId());
        long count = super.delete(Student.TABLE_NAME, contentValues);
        return count;
    }
    
    public ArrayList<Student> getAll(){
    	Cursor c = super.getAll(Student.TABLE_NAME, Student.DEFAULT_SORT_ORDER);
    	ArrayList<Student> array = new ArrayList<Student>();
    	if(c==null)
    		return array;
    	while(!c.isAfterLast()){
    		array.add(new Student(c));
    		c.moveToNext();
    	}
    	c.close();
    	return array;
    }
    
    public Student find(final int studentId) {
        ContentValues values = new ContentValues();
        values.put(Student.STUDENT_ID, studentId);
        Cursor c = super.find(Student.TABLE_NAME, values,Student.DEFAULT_SORT_ORDER);
        Student student = null;
        if (c != null) {
            try {
            	student = new Student(c);
            } catch (Exception e) {
            	e.printStackTrace();
			}
            finally {
                c.close();
            }
        }
        return student;
    }
    
    public boolean update(Student student){
    	boolean flag = true;
        ContentValues values = new ContentValues();
        values.put(Student.STUDENT_ID, student.getStudentId());
        values.put(Student.STUDENT_NAME, student.getStudentName());
        values.put(Student.ADDRESS, student.getAddress());
    	flag = super.update(Student.TABLE_NAME, values, Student.STUDENT_ID + "=?", new String[]{String.valueOf(student.getStudentId())})>0;
    	return flag;
    }
}
